package com.tiendung.otalunch;

import java.util.ArrayList;
import java.util.Calendar;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.SecretKeyFactory;
import javax.crypto.spec.DESKeySpec;

import org.apache.commons.codec.binary.Base64;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;

import android.app.Activity;
import android.app.Dialog;
import android.app.TimePickerDialog;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.TimePicker;

public class BookingTime extends Activity
{
	private static final String PASSPHRASE = "You can never guess me";
	private TextView timeDisplay;
	private int mHour;    
	private int mMinute;    
	private int mYear;
	private int mMonth;
	private int mDay;
	private OtaLunchDatabase db;
	
	private String restaurant_name;
	private String food_name;

	private TextView label;
	private Button submit;
	private Button cancel;
	
	static final int TIME_DIALOG_ID = 0;
	
	public void onCreate(Bundle savedInstanceState)
	{
		super.onCreate(savedInstanceState);
		setContentView(R.layout.bookingtime);	
		restaurant_name = getIntent().getStringExtra("Restaurant");
		food_name = getIntent().getStringExtra("Name");
		mYear = getIntent().getIntExtra("Year", 0);
		mMonth = getIntent().getIntExtra("Month", 0);
		mDay = getIntent().getIntExtra("Day", 0);
	
		label = (TextView) findViewById(R.id.label);
		timeDisplay = (TextView) findViewById(R.id.timeDisplay);
		submit = (Button) findViewById(R.id.submit);
		cancel = (Button) findViewById(R.id.cancel);
		
		label.setText("You are planning your lunch time for \"" + food_name + "\" at \"" + restaurant_name + "\"\n");
		
		// add a click listener to the button        
		timeDisplay.setOnClickListener(new View.OnClickListener() {            
			public void onClick(View v) {                
				showDialog(TIME_DIALOG_ID);            
			}        
		});        
		
		// get the current time        
		final Calendar c = Calendar.getInstance();        
		mHour = c.get(Calendar.HOUR_OF_DAY);        
		mMinute = c.get(Calendar.MINUTE);        
		this.db = new OtaLunchDatabase(this);
		
		// display the current date        
		updateDisplay();
		
		submit.setOnClickListener(new View.OnClickListener() {            
			public void onClick(View v) {  
				book(restaurant_name, mYear, mMonth, mDay, mHour, mMinute);
				finish();
			}        
		});  
		
		cancel.setOnClickListener(new View.OnClickListener() {            
			public void onClick(View v) {                
				
				finish();
			}        
		});  
	}
	
	private void book(String restaurant, int year, int month, int day, int hour, int minute)
    {
    	ArrayList<String> facebook_info = db.select_facebook();
    	
    	String url;
    	if (facebook_info.size() > 1)
    		url = "http://" + TheTabWidget.serverIP + "/book.php?action=add&id=" + encrypt(facebook_info.get(0)) + "&name=" + encrypt(facebook_info.get(1)) + "&restaurant=" + restaurant + "&year=" + mYear + "&month=" + (mMonth + 1) + "&day=" + mDay + "&hour=" + mHour + "&minute=" + mMinute;
    	else
    		url = "http://" + TheTabWidget.serverIP + "/book.php?action=add&id=NULL&name=NULL&restaurant=" + restaurant + "&year=" + mYear + "&month=" + (mMonth + 1) + "&day=" + mDay + "&hour=" + mHour + "&minute=" + mMinute;
    	
    	try {
    		DefaultHttpClient client = new DefaultHttpClient();
    		url = url.replace(" ", "%20");
        	HttpGet request = new HttpGet(url);	
        	client.execute(request);
		}
    	catch (Exception e) {}
    }
    
    private String encrypt(String input) {
		  DESKeySpec keySpec;
		  try {
				keySpec = new DESKeySpec(PASSPHRASE.getBytes("UTF8"));
				SecretKeyFactory keyFactory = SecretKeyFactory.getInstance("DES");
				SecretKey key = keyFactory.generateSecret(keySpec);
				  
				// ENCODE plainTextPassword String
				byte[] cleartext = input.getBytes("UTF8");      
				  
				Cipher cipher = Cipher.getInstance("DES"); // cipher is not thread safe
				cipher.init(Cipher.ENCRYPT_MODE, key);
				String encrypedPwd = new String(Base64.encodeBase64(cipher.doFinal(cleartext)));		  
				  
				return encrypedPwd;
		  } catch (Exception e) {
				e.printStackTrace();
		  }
		  
		  return null;
	   }
	
	// updates the time we display in the TextView
	private void updateDisplay() 
	{    
		timeDisplay.setText( new StringBuilder()                
			.append(pad(mHour)).append(":")                
			.append(pad(mMinute))
			.append(" " + pad(mDay) + "/" + pad(mMonth) + "/" + mYear + "\n"));
	}
	
	private static String pad(int c) 
	{    
		if (c >= 10)        
			return String.valueOf(c);    
		else        
			return "0" + String.valueOf(c);
	}
	
	@Override
	protected Dialog onCreateDialog(int id) {    
		switch (id) {    
			case TIME_DIALOG_ID:        
				return new TimePickerDialog(this, mTimeSetListener, mHour, mMinute, false);    
		}    
		
		return null;
	}
	
	// the callback received when the user "sets" the time in the dialog
	private TimePickerDialog.OnTimeSetListener mTimeSetListener = new TimePickerDialog.OnTimeSetListener() 
	{        
		public void onTimeSet(TimePicker view, int hourOfDay, int minute) 
		{            
			mHour = hourOfDay;            
			mMinute = minute;            
			updateDisplay();        
		}    
	};
}
